package vn.com.vega.chacha.v2;

import java.lang.ref.WeakReference;

import vn.com.vega.chacha.R;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.downloadmanager.DownloadUtil;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.MainMenuAdapter;
import vn.com.vega.music.view.adapter.MainScreenListsAdapter;
import vn.com.vega.music.view.custom.AdView;
import vn.com.vega.music.view.custom.BottomPlayerView;
import vn.com.vega.music.view.custom.BottomPlayerView.ShowHideBottomPlayerListener;
import vn.com.vega.music.view.custom.ChaChaDialog;
import vn.com.vega.music.view.custom.MyHorizontalScrollView;
import vn.com.vega.music.view.custom.MyHorizontalScrollView.SizeCallback;
import vn.com.vega.music.view.custom.TopTabSelectView;
import vn.com.vega.music.view.custom.TopTaskbarView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainScreen extends ActivityBase implements OnClickListener {
	private Appinstant mApp;
	private ViewPager mPaperView;
	private TopTabSelectView mTopTab;
	private MainScreenListsAdapter mMainAdapter;
	private BottomPlayerView mPlayerView;
	private TopTaskbarView mTopTaskbarView;

	private AdView mAdvertimentContent;
	private View mAdvertimentView;
	private ImageButton mCloseAdBtn;
	private View mWarningView;
	private TextView mWarningMessage;

	private View mMainScreen;
	private MyHorizontalScrollView mScrollView;
	// private View mAlbumDetail;
	// private View mListTabView;

	private View mMainMenu;
	private ImageView mUserThumb;
	private TextView mUserName;
	private ListView mListMainMenu;
	private View mViewRePlaceBottomPlayer;

	private ChaChaDialog mAppAboutDialog;
	private View mViewDisableClick;
	private DataStore mDataStore;

	public static final int UPDATE_PROGRESS = 1;
	public static final int AUTOHIDE_PLAYER = 2;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		mApp = (Appinstant) getApplication();
		Appinstant.isLogin = true;
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mScrollView = (MyHorizontalScrollView) inflater.inflate(R.layout.main,
				null);
		setContentView(mScrollView);

		// mAlbumDetail = findViewById(R.id.layout_album_detail);
		// mListTabView = findViewById(R.id.layout_list_main_tab);
		mTopTaskbarView = (TopTaskbarView) findViewById(R.id.topTaskbarView_player_screen);

		mMainMenu = inflater.inflate(R.layout.main_menu, null);
		Util.fixBackgroundRepeat(mMainMenu);
		mUserThumb = (ImageView) mMainMenu.findViewById(R.id.imv_user_thumb);
		mUserName = (TextView) mMainMenu.findViewById(R.id.tv_user_name);
		mDataStore = DataStore.getInstance();
		if (!Util.checkStringIsemptyOrNull(mDataStore
				.getConfig(Const.KEY_FULL_NAME))) {
			mUserName.setText(mDataStore.getConfig(Const.KEY_FULL_NAME));
		} else {
			mUserName.setText(mDataStore.getConfig(Const.KEY_PHONE_NUMBER));
		}
		mApp.mImageLoader.download(mDataStore.getConfig(Const.KEY_AVATAR),
				mUserThumb);
		mUserName.setOnClickListener(this);
		mUserThumb.setOnClickListener(this);

		mListMainMenu = (ListView) mMainMenu
				.findViewById(R.id.lv_list_main_menu);
		MainMenuAdapter mainMenuAdapter = new MainMenuAdapter(this);
		mListMainMenu.setAdapter(mainMenuAdapter);
		mListMainMenu.setOnItemClickListener(onMainMenuItemClickListener);
		gestureDetector = new GestureDetector(new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return gestureDetector.onTouchEvent(event);
			}
		};
		mListMainMenu.setOnTouchListener(gestureListener);

		mMainScreen = inflater.inflate(R.layout.main_screen, null);
		mTopTaskbarView = (TopTaskbarView) mMainScreen
				.findViewById(R.id.topTaskbarView1);
		mTopTab = (TopTabSelectView) mMainScreen
				.findViewById(R.id.topTabSelect_main_screen);
		mAdvertimentContent = (AdView) mMainScreen.findViewById(R.id.AdView);
		mAdvertimentView = mMainScreen.findViewById(R.id.view_advertiment);
		mCloseAdBtn = (ImageButton) mMainScreen
				.findViewById(R.id.bt_close_advertiment);
		mWarningView = mMainScreen.findViewById(R.id.view_warning);
		mWarningMessage = (TextView) mMainScreen
				.findViewById(R.id.tv_warning_message);
		showWarningAndAdvertiment();

		mPaperView = (ViewPager) mMainScreen
				.findViewById(R.id.paperview_mainscreen);
		mViewDisableClick = mMainScreen.findViewById(R.id.view_disable_click);
		mViewDisableClick.setVisibility(View.GONE);
		mViewDisableClick.setOnClickListener(this);
		mMainAdapter = new MainScreenListsAdapter(getSupportFragmentManager());
		mPaperView.setAdapter(mMainAdapter);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_SONG);
		mPaperView.setOnPageChangeListener(onPageChangeListener);

		mPlayerView = (BottomPlayerView) mMainScreen
				.findViewById(R.id.bottomPlayerView1);
		mViewRePlaceBottomPlayer = mMainScreen
				.findViewById(R.id.view_replace_bottom_player);
		mPlayerView.setShowHideListener(showHideBottomPlayerListener);
		mViewRePlaceBottomPlayer.setVisibility(View.GONE);

		mTopTaskbarView.getRealButtonBack().setOnClickListener(this);
		final View[] children = new View[] { mMainMenu, mMainScreen };
		// Scroll to app (view[1]) when layout finished.
		// int scrollToViewIdx = 1;
		mScrollView.initViews(children, 1, new SizeCallbackForMenu(this));

		// SyncUtil.startSync(getApplicationContext());
	}

	private void showWarningAndAdvertiment() {
		if (!Util.checkStringIsemptyOrNull(Appinstant.warningMessage)) {
			mWarningView.setVisibility(View.VISIBLE);
			mWarningMessage.setText(Appinstant.warningMessage);
			mWarningMessage.setSelected(true);
		}
		if (!Util.checkStringIsemptyOrNull(Appinstant.adMessage)) {
			mAdvertimentView.setVisibility(View.VISIBLE);
			mAdvertimentContent.setAdurl(Appinstant.adMessage);
			mAdvertimentContent.loadAd();
			mCloseAdBtn.setOnClickListener(this);
		}
	}

	private ShowHideBottomPlayerListener showHideBottomPlayerListener = new ShowHideBottomPlayerListener() {

		@Override
		public void onShowBottomPlayer() {
			// TODO Auto-generated method stub
			showBottomPlayer(true);
		}

		@Override
		public void onHideBottomPlayer() {
			// TODO Auto-generated method stub
			showBottomPlayer(false);
		}
	};

	AdapterView.OnItemClickListener onMainMenuItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			switch (position) {
			case 0:
				// Select online music
				gotoOnlineMusic();
				break;
			case 1:
				// Select personal music
				goToPersonalMusic();
				break;
			case 2:
				// Select search
				goToSearch();
				break;
			case 3:
				// Select how app info
				showAppInfo();
				break;
			case 4:
				// Exit app
				showMainMenu(false, false);
				confirmExitApp();
			default:
				break;
			}
		}
	};

	private void showAppInfo() {
		showMainMenu(false, false);
		if (mAppAboutDialog == null) {
			mAppAboutDialog = new ChaChaDialog(this, null);
			mAppAboutDialog.setTitle(getString(R.string.about_app));
			mAppAboutDialog.setMessage(getString(R.string.about_app_detail));
			mAppAboutDialog.hideCloseDefaultBtn();
			mAppAboutDialog.addDefaultOkBtn(getString(android.R.string.ok));
		}
		mAppAboutDialog.show();
	}

	private void goToSearch() {
		showMainMenu(false, false);
		Intent searchInten = new Intent(MainScreen.this, SearchScreen.class);
		startActivity(searchInten);
	}

	private void goToPersonalMusic() {
		showMainMenu(false, false);
		Intent intent = new Intent(MainScreen.this, PersonalMusic.class);
		startActivity(intent);
	}

	private void gotoOnlineMusic() {
		showMainMenu(false, true);
		changeToFeatureSong();
	}

	private void goToPersonalSetting() {
		showMainMenu(false, false);
		Intent intent = new Intent(MainScreen.this, SettingAccount.class);
		startActivity(intent);
	}

	private void showMainMenu(boolean show, boolean smooth) {
		if (show) {
			if (smooth) {
				mScrollView.smoothScrollTo(0, 0);
			} else {
				mScrollView.scrollTo(0, 0);
			}
			mViewDisableClick.setVisibility(View.VISIBLE);
		} else {
			if (smooth) {
				mScrollView.smoothScrollTo(mMainMenu.getMeasuredWidth(), 0);
			} else {
				mScrollView.scrollTo(mMainMenu.getMeasuredWidth(), 0);
			}

			mViewDisableClick.setVisibility(View.GONE);
		}
	}

	private void showBottomPlayer(boolean show) {
		if (show) {
			mViewRePlaceBottomPlayer.setVisibility(View.VISIBLE);
		} else {
			mViewRePlaceBottomPlayer.setVisibility(View.GONE);
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		mPlayerView.stopUpdate();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		// TODO: check have need clean app here, because service still run on
		// background
		// mApp.cleanApp();
		DownloadUtil.unbindAll();
		Util.unbindAll();
		// /*LocalBroadcastManager.getInstance(this).*/unregisterReceiver(mPlayerView.playerBroadcastReceiver);
		// update.removeCallbacksAndMessages(null);
		// SyncUtil.stopSync(getApplicationContext());
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mPlayerView.startUpdate();
		showMainMenu(false, false);
	}

	private ChaChaDialog exitDialog;

	private void confirmExitApp() {
		if (exitDialog == null) {
			exitDialog = new ChaChaDialog(this, null);
			exitDialog.setCancelable(true);
			exitDialog.setTitle("Thoát?");
			exitDialog.setMessage("Bạn muốn thoát ứng dụng?");
			View.OnClickListener yesClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					exitDialog.dismiss();
					Util.stop();
					DownloadUtil.stopDownload();
//					SyncUtil.stopSync(getApplicationContext());
					finish();
				}
			};

			View.OnClickListener noClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					exitDialog.dismiss();
				}
			};
			exitDialog.addButton(getString(R.string.confirm_yes),
					yesClickListener);
			exitDialog.addButton(getString(R.string.confirm_no),
					noClickListener);
		}
		exitDialog.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (mPlayerView.mLayoutListPlay.isShown()) {
			mPlayerView.hideListSong();
			return;
		}

		if (mTopTaskbarView.isShowSearchBox()) {
			mTopTaskbarView.hideSearchBox();
			return;
		}
		// if (mAlbumDetail.isShown()) {
		// showListMainTab();
		// return;
		// }
		if (Util.isPlaying()) {
			Intent homeIntent = new Intent(Intent.ACTION_MAIN);
			homeIntent.addCategory(Intent.CATEGORY_HOME);
			homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(homeIntent);
			return;
		}
		confirmExitApp();
		// super.onBackPressed();
	}

	/**
	 * Helper for examples with a HSV that should be scrolled by a menu View's
	 * width.
	 */
	static class ClickListenerForScrolling implements OnClickListener {
		HorizontalScrollView scrollView;
		View menu;
		/**
		 * Menu must NOT be out/shown to start with.
		 */
		boolean menuOut = false;

		public ClickListenerForScrolling(HorizontalScrollView scrollView,
				View menu) {
			super();
			this.scrollView = scrollView;
			this.menu = menu;
		}

		@Override
		public void onClick(View v) {
			int menuWidth = menu.getMeasuredWidth();
			// Ensure menu is visible
			menu.setVisibility(View.VISIBLE);

			if (!menuOut) {
				// Scroll to 0 to reveal menu
				int left = 0;
				scrollView.smoothScrollTo(left, 0);
			} else {
				// Scroll to menuWidth so menu isn't on screen.
				int left = menuWidth;
				scrollView.smoothScrollTo(left, 0);
			}
			menuOut = !menuOut;
		}
	}

	/**
	 * Helper that remembers the width of the 'slide' button, so that the
	 * 'slide' button remains in view, even when the menu is showing.
	 */
	static class SizeCallbackForMenu implements SizeCallback {
		int btnWidth;
		// View btnSlide;
		WeakReference<MainScreen> mainRfc;

		public SizeCallbackForMenu(MainScreen main) {
			super();
			// this.btnSlide = btnSlide;
			mainRfc = new WeakReference<MainScreen>(main);
			btnWidth = (int) main.getResources().getDimension(
					R.dimen.main_menu_margin_right);
		}

		@Override
		public void onGlobalLayout() {
			// btnWidth = btnSlide.getMeasuredWidth();
			// VegaLog.e("btnWidth=" + btnWidth);
		}

		@Override
		public void getViewSize(int idx, int w, int h, int[] dims) {
			dims[0] = w;
			dims[1] = h;
			final int menuIdx = 0;
			if (idx == menuIdx) {
				dims[0] = w - btnWidth;
			}
		}
	}

	private void changeToFeatureSong() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_SONG);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_SONG);
	}

	private void changeToFeatureVideo() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_VIDEO);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_VIDEO);
	}

	private void changeToFeatureAlbum() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_ALBUM);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_ALBUM);
	}

	private void changeToFeaturePlaylist() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_PLAYLIST);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_PLAYLIST);
	}

	private void changeToFeatureChart() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_CHART);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_CHART);
	}

	private void changeToFeatureNews() {
		mPaperView
				.setCurrentItem(MainScreenListsAdapter.INDEX_LIST_FEATURE_NEWS);
		setToptab(MainScreenListsAdapter.INDEX_LIST_FEATURE_NEWS);
	}

	private void setToptab(int indexTab) {
		switch (indexTab) {
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_SONG:
			mTopTab.setLeftText(getString(R.string.feature_song_title), null,
					true);

			mTopTab.setCenterText(getString(R.string.feature_video_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureVideo();
						}
					}, false);
			mTopTab.setRightText(getString(R.string.feature_album_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureAlbum();
						}
					}, false);
			break;
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_VIDEO:
			mTopTab.setLeftText(getString(R.string.feature_song_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureSong();
						}
					}, false);
			mTopTab.setCenterText(getString(R.string.feature_video_title),
					null, true);
			mTopTab.setRightText(getString(R.string.feature_album_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureAlbum();
						}
					}, false);
			break;
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_ALBUM:
			mTopTab.setLeftText(getString(R.string.feature_video_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureVideo();
						}
					}, false);
			mTopTab.setCenterText(getString(R.string.feature_album_title),
					null, true);
			mTopTab.setRightText(getString(R.string.feature_playlist_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeaturePlaylist();
						}
					}, false);
			break;
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_PLAYLIST:
			mTopTab.setLeftText(getString(R.string.feature_album_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureAlbum();
						}
					}, false);
			mTopTab.setCenterText(getString(R.string.feature_playlist_title),
					null, true);
			mTopTab.setRightText(getString(R.string.feature_billboard_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureChart();
						}
					}, false);
			break;
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_CHART:
			mTopTab.setLeftText(getString(R.string.feature_playlist_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeaturePlaylist();
						}
					}, false);
			mTopTab.setCenterText(getString(R.string.feature_billboard_title),
					null, true);
			mTopTab.setRightText(getString(R.string.feature_news_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureNews();
						}
					}, false);
			break;
		case MainScreenListsAdapter.INDEX_LIST_FEATURE_NEWS:
			mTopTab.setLeftText(getString(R.string.feature_playlist_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeaturePlaylist();
						}
					}, false);
			mTopTab.setCenterText(getString(R.string.feature_billboard_title),
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							changeToFeatureChart();
						}
					}, false);
			mTopTab.setRightText(getString(R.string.feature_news_title), null,
					true);
			break;

		default:
			break;
		}
	}

	OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			setToptab(arg0);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mTopTaskbarView.getRealButtonBack()) {
			mTopTaskbarView.hideSearchBox();
			if (mainMenuIsShow()) {
				// Hide main menu
				showMainMenu(false, true);
			} else {
				// Show main menu
				showMainMenu(true, true);
			}
		} else if (v == mViewDisableClick) {
			showMainMenu(false, true);
		} else if (v == mUserName || v == mUserThumb) {
			goToPersonalSetting();
		} else if (v == mCloseAdBtn) {
			mAdvertimentView.setVisibility(View.GONE);
		}
	}

	private boolean mainMenuIsShow() {
		Rect scrollBounds = new Rect();
		mScrollView.getHitRect(scrollBounds);
		if (mMainMenu.getLocalVisibleRect(scrollBounds)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void appLogouted() {
		Appinstant.isLogin = false;
		mApp.clearUserData();
		super.appLogouted();
	}

	private static final int SWIPE_MIN_DISTANCE = 40;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;

	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					// Left Swipe
					showMainMenu(false, true);
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					// Right Swipe
					// Do no thing here
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}

	}
}
